package dk.fuddi.grails

import grails.converters.JSON

class ToiletController {

  static navigation = [
      group: 'tabs',
      order: 20,
      title: 'Toilets',
      action: 'index'
  ]

  def index = { redirect(action: list, params: params) }
  def toiletService

  // the delete, save and update actions only accept POST requests
  static allowedMethods = [delete: 'POST', save: 'POST', update: 'POST']

  def list = {
    params.max = Math.min(params.max ? params.max.toInteger() : 10, 100)
    def toiletList = Toilet.list(params)

    if (params.json != null) {
      getJSONFormat(toiletList)
    } else {
      [toiletInstanceList: toiletList, toiletInstanceTotal: Toilet.count()]
    }
  }

  def getJSONFormat(List<Toilet> toiletList) {
    HashMap jsonMap = new HashMap()
    jsonMap.total = Toilet.count()
    jsonMap.toilets = toiletList.collect {t ->
      return [id: t.id, address: t.address, zipCode: t.zipCode, city: t.city, lat: t.lat, lng: t.lng,
          type: t.type.toString(), paymentFree: t.paymentFree.toString()]
    }
    render jsonMap as JSON
  }

  def show = {
    def toiletInstance = Toilet.get(params.id)

    if (!toiletInstance) {
      flash.message = "Toilet not found with id ${params.id}"
      redirect(action: list)
    }
    else { return [toiletInstance: toiletInstance] }
  }

  def delete = {
    Toilet.withTransaction {
      def toiletInstance = Toilet.get(params.id)
      if (toiletInstance) {
        try {
          toiletInstance.delete(flush: true)
          flash.message = "Toilet ${params.id} deleted"
          redirect(action: list)
        }
        catch (org.springframework.dao.DataIntegrityViolationException e) {
          flash.message = "Toilet ${params.id} could not be deleted"
          redirect(action: show, id: params.id)
        }
      }
      else {
        flash.message = "Toilet not found with id ${params.id}"
        redirect(action: list)
      }
    }
  }

  def edit = {
    def toiletInstance = Toilet.get(params.id)

    if (!toiletInstance) {
      flash.message = "Toilet not found with id ${params.id}"
      redirect(action: list)
    }
    else {
      return [toiletInstance: toiletInstance]
    }
  }

  def update = {
    Toilet.withTransaction {
      def toiletInstance = Toilet.get(params.id)
      if (toiletInstance) {
        if (params.version) {
          def version = params.version.toLong()
          if (toiletInstance.version > version) {

            toiletInstance.errors.rejectValue("version", "toilet.optimistic.locking.failure", "Another user has updated this Toilet while you were editing.")
            render(view: 'edit', model: [toiletInstance: toiletInstance])
            return
          }
        }
        toiletInstance.properties = params
        if (!toiletInstance.hasErrors() && toiletInstance.save()) {
          flash.message = "Toilet ${params.id} updated"
          redirect(action: show, id: toiletInstance.id)
        }
        else {
          render(view: 'edit', model: [toiletInstance: toiletInstance])
        }
      }
      else {
        flash.message = "Toilet not found with id ${params.id}"
        redirect(action: list)
      }
    }
  }

  def create = {
    def toiletInstance = new Toilet()
    toiletInstance.properties = params
    return ['toiletInstance': toiletInstance]
  }

  def save = {
    def toiletInstance = new Toilet(params)
    Toilet.withTransaction {
      if (toiletInstance.save(flush: true)) {
        flash.message = "Toilet ${toiletInstance.id} created"
        redirect(action: show, id: toiletInstance.id)
      }
      else {
        render(view: 'create', model: [toiletInstance: toiletInstance])
      }
    }
  }

  def refreshToilets = {
    def toilets = toiletService.getToilets()
    int savedToilets = 0
    for (t in toilets) {
      Toilet.withTransaction {
        def savedToilet = Toilet.findWhere(nid: t.nid)
        if (savedToilet == null) {
          log.debug "Save new toilet with nid $t.nid"
          t.save()
          savedToilets++
        }
      }
    }
    render(view: 'refreshToilets', model: [savedToilets: savedToilets])
  }
}
